// 宁波银行分片做法

import SparkMD5 from 'spark-md5';

export function calculateMD5(file) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    const spark = new SparkMD5.ArrayBuffer();
    reader.onload = e => {
      spark.append(e.target.result); // 计算当前块的哈希（耗时操作）
      const md5 = spark.end();
      resolve(md5);
    };
    reader.onerror = () => { reject('读取文件时出错'); };
    reader.readAsArrayBuffer(file.raw); // 文件读取（IO操作，耗时）
  });
}

export function cutFile(file, chunkSize) {
  const chunks = [];
  let start = 0;
  let end = 0;
  while (start < file.size) {
    end = Math.min(start + chunkSize, file.size);
    const chunk = {
      chunk: file.raw.slice(start, end),
      currentChunkSize: end < file.size ? chunkSize : file.szie % chunkSize
    };
    chunks.push(chunk);
    start = end;
  }
}
